package lena;

import java.awt.image.BufferedImage;
import java.io.PrintStream;
import lib.Actor;
import lib.ActorAddress;
import lib.Message;

public class CutterActor extends Actor{
	private static final int NB_PARTS = 4;
	private BufferedImage reconstitutes_img;
	private int iDImg = 0; 


	public CutterActor(ActorAddress superActor,ActorAddress myAddress) throws Exception {
		super(superActor, myAddress, "CutterActor");
		startActor();
	}

	protected boolean standardRoutine() throws Exception {
		this.standardRoutineIsUsed=false;
		return true;
	}

	protected boolean handleMessage(Message msg) throws Exception {
		if (msg.getOperation().equals("Terminate")) {
			return false;
		}   
		System.out.println("CuterActor: image received");
		BufferedImage img = ((SentImage)msg.getContent()).getImage();
		this.iDImg++;
		String destActorType;
		String operation=msg.getOperation();
		if (operation.equals("Mirror")){
			destActorType="MirrorActor";
		} else if (operation.equals("Binarize")){
			destActorType="BinarizeActor";
		} else if (operation.equals("NoirBlanc")){
			destActorType="NoirBlancActor";
		} else if (operation.equals("Mix")){
			destActorType="Mix";
		}  else {
			destActorType=null;
		}
		
		if (destActorType==null){
			System.out.println("CutterActor: Undefined operation");
		} else if (destActorType.equals("Mix")){
			for (int i = 0; i < this.NB_PARTS; i++) {
				BufferedImage part = new BufferedImage(img.getWidth(), img.getHeight() / 4, img.getType());
				int[] pixel = new int[part.getWidth() * part.getHeight()];
				img.getRGB(0, i * part.getHeight(), part.getWidth(), part.getHeight(), pixel, 0, part.getWidth());
				part.setRGB(0, 0, part.getWidth(), part.getHeight(), pixel, 0, part.getWidth());
				ImgChunk chunk = new ImgChunk(i, this.NB_PARTS, part,this.iDImg);
				switch(i%3){
					case 0:
						sendMsg(new Message(this.myAddress, "CutterActor","MirrorActor", "", "new", chunk));
						break;
					case 1:
						sendMsg(new Message(this.myAddress, "CutterActor","NoirBlancActor", "", "new", chunk));
						break;
					case 2:
						sendMsg(new Message(this.myAddress, "CutterActor","BinarizeActor", "", "new", chunk));
						break;
				}
			}
		} else {
			for (int i = 0; i < this.NB_PARTS; i++) {
				BufferedImage part = new BufferedImage(img.getWidth(), img.getHeight() / 4, img.getType());
				int[] pixel = new int[part.getWidth() * part.getHeight()];
				img.getRGB(0, i * part.getHeight(), part.getWidth(), part.getHeight(), pixel, 0, part.getWidth());
				part.setRGB(0, 0, part.getWidth(), part.getHeight(), pixel, 0, part.getWidth());
				ImgChunk chunk = new ImgChunk(i, this.NB_PARTS, part,this.iDImg);
				sendMsg(new Message(this.myAddress, "CutterActor",destActorType, "", "new", chunk));
			}
		}
		return true;
	}
}

